package cn.hchaojie.camp.week2.qa;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DemoCP {
	public static void main(String[] args) {
		Factory f = new Factory();
		
		ExecutorService executor = Executors.newFixedThreadPool(2);
		executor.execute(new Producer(f));
		executor.execute(new Consumer(f));
		
		executor.shutdown();
	}
	
	static class Producer implements Runnable {
		Factory factory;
		public Producer(Factory f) {
			this.factory = f;
		}

		@Override
		public void run() {
			try {
				while (true) {
					Thread.sleep((long) (Math.random() * 100));
					factory.put();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	static class Consumer implements Runnable {
		Factory factory;
		public Consumer(Factory f) {
			this.factory = f;
		}

		@Override
		public void run() {
			try {
				while (true) {
					Thread.sleep((long) (Math.random() * 100));
					factory.take();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	static class Factory {
		private static final int MAX = 10;
		private List<Integer> eggs = new ArrayList<>();

		private int count = 0;
		
		public synchronized void put() {
			if (count == MAX) {
				try {
					System.out.println("不能放了！, 等别人拿一个再说");
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			count++;
			System.out.println("放入一个 #" + count);

			notify();
		}
		
		public synchronized void take() {
			if (count == 0) {
				try {
					System.out.println("没东西了！, 先等等看八");
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			System.out.println("哈哈抢到了 #" + count);
			count--;
			
			notify();
		}
	}
}
